package com.powernode.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.domain.Basket;
import com.powernode.service.BasketService;
import com.powernode.utils.AuthUtil;
import com.powernode.vo.CartTotalAmount;
import com.powernode.vo.CartVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "购物车接口管理")
@RestController
@RequestMapping("/p/shopCart")
public class BasketController {
    @Autowired
    private BasketService basketService;

    @ApiOperation("查询购物车中数量")
    @GetMapping("/prodCount")
    public ResponseEntity<Integer> loadCartCount() {
        Integer count = basketService.loadCartCount();
        return ResponseEntity.ok(count);
    }

    @ApiOperation("查询用户购物车详情")
    @GetMapping("/info")
    public ResponseEntity<CartVo> loadUserCartVoInfo() {
        String userId = AuthUtil.getLoginUserId();
        CartVo cartVo = basketService.selectUserBasketInfo(userId);
        return ResponseEntity.ok(cartVo);
    }

    @ApiOperation("查询购物车总计")
    @PostMapping("/totalPay")
    public ResponseEntity<CartTotalAmount> loadUserCartTotalAmount(@RequestBody List<Long> basketIds) {
        String userId = AuthUtil.getLoginUserId();
        CartTotalAmount cartTotalAmount = basketService.selectUserCartTotalAmount(userId, basketIds);
        return ResponseEntity.ok(cartTotalAmount);
    }

    @ApiOperation("加入或修改购物车商品sku数量")
    @PostMapping("/changeItem")
    public ResponseEntity<Void> addAndModifyBasketProdCount(@RequestBody Basket basket) {
        String userId = AuthUtil.getLoginUserId();
        basket.setUserId(userId);
        basketService.addAndModifyBasketProdCount(basket);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("删除购物车条目")
    @DeleteMapping("/deleteItem")
    public ResponseEntity<Void> deleteItem(@RequestBody List<Long> basketIds) {
        basketService.removeByIds(basketIds);
        return ResponseEntity.ok().build();
    }


    ////////////////////// 远程接口调用 ///////////////////

    @GetMapping("/getBasketsByIds")
    List<Basket> getBasketsByIds(@RequestParam List<Long> basketIds) {
        return basketService.listByIds(basketIds);
    }

    @PostMapping("/clearBasketSkuList")
    Boolean clearBasketSkuList(@RequestBody List<Long> skuIdList, @RequestParam String userId) {
        return basketService.remove(new LambdaQueryWrapper<Basket>()
            .eq(Basket::getUserId, userId)
                .in(Basket::getSkuId, skuIdList)
        );
    }
}
